<template>
  <div class="container">
    <div class='login_content'>
      <div class='user_photo'><open-data type="userAvatarUrl"></open-data></div>
      <div class='user_nickname'><open-data type="userNickName"></open-data></div>
      <button  v-if="canIUse" class="login_btn" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">点击授权登录</button>
      <div v-else>请升级微信版本</div>
      <button @click="navigateToHome">返回首页</button>
    </div>
  </div>
</template>
<script>
import { postCode } from '../../api/index.js'
import { mapActions } from 'vuex'

export default {
  data () {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo'), //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    }
  },
  methods: {
    ...mapActions(['_reqUserInfo']),
    bindGetUserInfo(e){
      var This = this;
      let code = this.$store.state.userCode;
      wx.getUserInfo({
        lang : 'zh_CN',
        success : res => {
          This.$store.dispatch('_setWXUserInfo',res); //将用户信息保存的VUEX
          let parmas = {
            raw_data:res.rawData,
            signature:res.signature,
            code:code
          };
          //发送code到服务器获取数据
          postCode(parmas).then(respones => {
            if(respones.data.level=="success"){
              wx.setStorageSync('userToken',respones.data.data);
              this._reqUserInfo();//获取后端用户信息
              wx.switchTab({
                url:"/pages/home/main"
              })
            }else{
              wx.showToast(respones.data.message,'none',1000)
            }
          })
        }
      })
    },
    navigateToHome(){
      wx.switchTab({
        url: "/pages/home/main"
      })
    }
  },
}
</script>
<style lang="stylus" scoped>
.container
  width 100%
  height 100vh
  display flex
  justify-content center
  align-items center
  .login_content
    width 70%
    display flex
    flex-direction column
    justify-content center
    align-items center
    position relative
    top -100rpx
    .user_photo
      width 150rpx
    .user_nickname
      text-align center
      margin-top 20px
    button
      font-size 14px
      margin-top 30rpx
      border-radius 10rpx
      width 54%
      background-color green
      color #fff
</style>
